package rsj.service;

import com.rlyy.aibase.db.Dbink;
import common.exec.RsjIllegalArgueException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rsj.db.PostgresqlConn;
import common.util.QueryRunnerFactory;

import java.sql.Connection;
import java.util.function.Consumer;
import java.util.function.Function;

/**
 * @author yuanqinglong
 * @since 2021/3/31 9:38
 */
public interface IExecuteInterface {

    Logger logger = LoggerFactory.getLogger(IExecuteInterface.class);

    /**
     * 执行查询sql 统一处理异常等信息
     *
     * @param function 执行体
     * @param log 记录日志
     * @return 返回数据
     */
    static Object doExecuteQuery(Function<Connection, Object> function, Consumer<Object> log) {
        Connection connection = PostgresqlConn.getConnection();
        Object result;
        try {
            result = function.apply(connection);
        } catch (Exception e) {
            log.accept(e);
            throw new RsjIllegalArgueException("服务异常");
        } finally {
            Dbink.close(connection);
        }
        return result;
    }


    /**
     * 执行修改sql 统一处理异常等信息
     *
     * @param sql 执行的语句
     * @param log 日志
     * @return 返回数据
     */
    static Object doExecuteUpdate(String sql, Consumer<Object> log) {
        Connection connection = PostgresqlConn.getConnection();
        Object result;
        try {
            result = QueryRunnerFactory.getQueryRunner().update(connection, sql);
        } catch (Exception e) {
            log.accept(e);
            throw new RsjIllegalArgueException("服务异常");
        } finally {
            Dbink.close(connection);
        }
        return result;
    }
}
